package com.my;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by YJH on 2017/7/12 23:18.
 */
public class AuthorityServlet extends HttpServlet {

    private UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methodName = request.getParameter("method");

        try {
            Method method = getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getAuthorities(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        User user = userDao.get(username);

        request.setAttribute("user", user);
        request.setAttribute("authorityList", userDao.getAuthorityList());
        request.getRequestDispatcher("/authority-manager.jsp").forward(request, response);   //转发
    }

    public void updateAuthority(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String[] authorities = request.getParameterValues("authority");
        List<Authority> authorityList = userDao.getAuthorityList(authorities);
        userDao.update(username, authorityList);
        response.sendRedirect(request.getContextPath() + "/authority-manager.jsp");
    }
}
